package com.tushare.controller;

import com.tushare.entity.TimeShareChart;
import com.tushare.network.WapRequest;
import com.tushare.service.ITimeShareChartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin("*")
public class SinaFinanceController {
    @Autowired
    ITimeShareChartService timeShareChartService;
    @Autowired
    RestTemplate restTemplate;

    /**
     * 获取分时图
     * https://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sz000063&scale=5&datalen=1023
     * 获取sz000063五分钟的分时数据，最大只能取1023条
     * 有频率限制
     *
     * @param ts_code 股票代码
     */
    @GetMapping(value = "timeShareChart", params = {"ts_code"})
    public List<TimeShareChart> getTimeShareChart(@RequestParam("ts_code") String ts_code) {
        String sinaCode = ts_code.toLowerCase();
        sinaCode = sinaCode.substring(7, 9) + sinaCode.substring(0, 6);
        String apiUrl = "https://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=";
        apiUrl += sinaCode;
        apiUrl += "&scale=5&datalen=1023";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Referer", "http://finance.sina.com.cn");
        WapRequest params = new WapRequest();
        HttpEntity<WapRequest> entity = new HttpEntity<>(params, httpHeaders);
        ParameterizedTypeReference<List<TimeShareChart>> typeRef = new ParameterizedTypeReference<>() {
        };
        System.out.println(apiUrl);
        ResponseEntity<List<TimeShareChart>> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.GET, entity, typeRef);
        List<TimeShareChart> timeShareChartList = responseEntity.getBody();
        if (timeShareChartList == null || timeShareChartList.size() == 0) {
            return new ArrayList<>();
        }
        timeShareChartList.forEach(timeShareChart -> timeShareChart.setTs_code(ts_code));
        timeShareChartService.deleteTimeShareChartByTsCode(ts_code);
        timeShareChartService.saveOrUpdateBatch(timeShareChartList);
        return timeShareChartList;
    }
}
